package com.zm.devmag.back.web;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.swetake.util.Qrcode;
import com.zm.devmag.back.vo.Admin;
import com.zm.devmag.device.Vo.DeviceDetaiVo;
import com.zm.devmag.device.Vo.InOutStockVo;
import com.zm.devmag.device.dao.WarehouseMapper;
import com.zm.devmag.device.po.Category;
import com.zm.devmag.device.po.DeviceDetail;
import com.zm.devmag.device.po.InOutStock;
import com.zm.devmag.device.po.TempData;
import com.zm.devmag.device.po.Warehouse;
import com.zm.devmag.device.service.CategoryServer;
import com.zm.devmag.device.service.DeviceDetailServer;
import com.zm.devmag.device.service.IOSTempServer;
import com.zm.devmag.device.service.InOutStockServer;
import com.zm.devmag.user.po.Users;
import com.zm.devmag.user.server.UsersServer;
import com.zm.devmag.util.EncoderHandler;
import com.zm.devmag.util.ExcelUtil;
import com.zm.devmag.util.TscPrint;


import org.springframework.ui.Model;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;


@Controller
@RequestMapping("/back")
public class BackController {
	
	@Autowired
	private UsersServer userService;
	@Autowired
	private CategoryServer categService;
	@Autowired
	private DeviceDetailServer ddService;
	@Autowired
	private InOutStockServer iosService;
	@Autowired
	private IOSTempServer iostService;
	//首页
	@RequestMapping("/index")
	public ModelAndView index(){
		return new ModelAndView("back/devicelist");
	}
	//用户列表
	@RequestMapping("/userlist")
	public ModelAndView UsersList(){
		Map<String,Object> model = new HashMap<String,Object>();
		List<Users> users = userService.findAll(null,null);
		model.put("users", users);
	
		return new ModelAndView("back/users/ulist",model);
	}
	//添加新用户
	@RequestMapping("/useraddShow")
	public ModelAndView userAddShow(){
		Map<String,Object> model = new HashMap<String,Object>();
		return new ModelAndView("back/users/uadd",model);
	}
	@ResponseBody
	@RequestMapping("/useradd")
	//@RequestMapping(value="/useradd",produces="application/json;charset=UTF-8;")
	public Object userAdd(Users user){
		Map<String, Object> reJson = new HashMap<String, Object>();
		Long maxId = whMapper.getMaxIdValue();
		if(whMapper.selectNameCountByWhname(user.getWorkname())<=0){
			Warehouse wh = new Warehouse();
			wh.setId(maxId+1);
			wh.setWhname(user.getWorkname());
			whMapper.insertSelective(wh);
		}
		Warehouse wh = whMapper.selectWHByWhname(user.getWorkname());
		if(wh!=null) {
			user.setWid(wh.getId());
			if(userService.insertSelective(user)>0)
				reJson.put("ok", "ok");
			else
				reJson.put("ok", "fal");
		}
		return JSON.toJSONString(reJson);
	}
	//修改用户
	
	@RequestMapping("/usermodShow")
	public ModelAndView userModShow(Long uid,Model model){
		Users user = userService.selectByPrimaryKey(uid);
		model.addAttribute("user",user);
		return new ModelAndView("back/users/umod");
	}
	@ResponseBody
	@RequestMapping("/usermod")
	public Object userMod(Users user){
		Map<String, Object> reJson = new HashMap<String, Object>();
		if(userService.updateByUserData(user)>0) {
			reJson.put("ok", "ok");
		}else {
			reJson.put("ok", "fal");
		}
		return JSON.toJSONString(reJson);
	}
	//删除用户
	@RequestMapping("/userdel")
	public ModelAndView userDel(Long uid, @RequestParam(required = false,defaultValue = "1") int pageNo,
            @RequestParam(required = false,defaultValue = "10") int limit){
		userService.deleteByPrimaryKey(uid);
		return new ModelAndView("redirect:/back/userlist.do");
	}
	
	//设备分类
	@RequestMapping("/deviceflshow")
	public ModelAndView deviceFLShow(Model model){
		List<Category> catag = categService.findAll();
		model.addAttribute("catag",catag);
		return new ModelAndView("back/device/devicefl");
	}
	//设备操作
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/devicelist",method = {RequestMethod.GET,RequestMethod.POST})
	public ModelAndView deviceList(@RequestParam(required = false,defaultValue = "0")String status, Long wid,
			String dcid,String pxtype,Model model, String stcsj,String stcsjd1,String stcsjd2,
			@RequestParam(required = false,defaultValue = "1") int pageNo,HttpServletRequest request){
		Map<String,Object> cond = new HashMap<String,Object>();
		//String dcid=(String)request.getParameter("dcid");
		String dcide="";
		/*try {
			dcide = new String(request.getParameter("dcid").getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}*/
		if(dcid != null && !dcid.equals("")) {

			try {			
				dcide = URLDecoder.decode(dcid, "UTF-8");
			} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
			}
			
			
		}
		cond.put("wid", wid);
		cond.put("dcid", dcide);
		cond.put("stcsj", stcsj);
		cond.put("stcsjd1", stcsjd1);
		cond.put("stcsjd2", stcsjd2);
		//@SuppressWarnings("unchecked")
		Map<String,Object> sscond = (Map<String, Object>) request.getSession().getAttribute("cond");
		//@SuppressWarnings("unchecked")
		Map<String,Object> pxcond; //=(Map<String,Object>) sscond.get("pxcond");
		if(sscond ==null) {
			pxcond = new HashMap<String,Object>();
			pxcond.put("jbhpx", false);
			pxcond.put("bhpx", false);
			pxcond.put("xhpx", false);
			pxcond.put("ccbhpx", false);
			pxcond.put("tcnypx", false);
			pxcond.put("zjnxpx", false);
			pxcond.put("cgjapx", false);
			pxcond.put("sblbpx", false);
			pxcond.put("ckwzpx", false);
			cond.put("pxcond", pxcond);
		}else {
			pxcond = (Map<String,Object>) sscond.get("pxcond");
			if(pxcond == null) {
				pxcond = new HashMap<String,Object>();
				pxcond.put("jbhpx", false);
				pxcond.put("bhpx", false);
				pxcond.put("xhpx", false);
				pxcond.put("ccbhpx", false);
				pxcond.put("tcnypx", false);
				pxcond.put("zjnxpx", false);
				pxcond.put("cgjapx", false);
				pxcond.put("sblbpx", false);
				pxcond.put("ckwzpx", false);
				cond.put("pxcond", pxcond);
			}
		}
		if(!status.equals("0"))
			cond.put("status", status);
		if(pxtype!=null) {
			for (Map.Entry<String, Object> entry : pxcond.entrySet()) { 
				  System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
				  if(entry.getKey().equals(pxtype)) {
					  entry.setValue(!((Boolean) entry.getValue()));
				  }else {
					  entry.setValue(false);
				  }
				}
			pxcond.put("select", pxtype);
			cond.put("pxcond", pxcond);
			//cond.put(pxtype,!((Boolean)cond.get(pxtype)));
			/*String ty= cond.get(pxtype).toString();
			if(ty.equals("DESC")) {
				cond.put(pxtype, "ASC");
			}else {
				cond.put(pxtype, "DESC");
			}*/
			
		}
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		if(!admin.getUtype().equals("1")){
			Users user = userService.SelectUserByUacc(admin.getName()) ;
			if(wid ==null)
				cond.put("wid", user.getWid());
			List<Warehouse> whlist= whMapper.findAll();
			model.addAttribute("whlist",whlist);
		}else{
			List<Warehouse> whlist= whMapper.findAll();
			model.addAttribute("whlist",whlist);
		}
		cond.put("pageNo", pageNo);
		request.getSession().setAttribute("cond", cond);
		int listlen=ddService.selectAllCount(cond);
		
		List<Category>maxc = categService.getCategroyByCtype("1");
		List<Category>midc = categService.getCategroyByCtype("2");
		List<Category>shac = categService.getCategroyByCtype("3");
		List<Warehouse> whlist= whMapper.findAll();
        List<String> nolist = ddService.selectAllDeviceNo();
		
		model.addAttribute("listlen",listlen);
		model.addAttribute("maxc",maxc);
		model.addAttribute("midc",midc);
		model.addAttribute("shac",shac);
		model.addAttribute("nolist",nolist);
		model.addAttribute("pageNo",pageNo);
		model.addAttribute("status",status);
		model.addAttribute("wid",cond.get("wid"));
		model.addAttribute("dcid",cond.get("dcid"));
		model.addAttribute("stcsj",cond.get("stcsj"));
		model.addAttribute("stcsjd1",cond.get("stcsjd1"));
		model.addAttribute("stcsjd2",cond.get("stcsjd2"));
		model.addAttribute("whlist",whlist);
		
		model.addAttribute("jbhpx", pxcond.get("jbhpx"));
		model.addAttribute("bhpx", pxcond.get("bhpx"));
		model.addAttribute("xhpx", pxcond.get("xhpx"));
		model.addAttribute("ccbhpx", pxcond.get("ccbhpx"));
		model.addAttribute("tcnypx", pxcond.get("tcnypx"));
		model.addAttribute("zjnxpx", pxcond.get("zjnxpx"));
		model.addAttribute("cgjapx", pxcond.get("cgjapx"));
		model.addAttribute("sblbpx", pxcond.get("sblbpx"));
		model.addAttribute("ckwzpx", pxcond.get("ckwzpx"));
		return new ModelAndView("back/device/devicelist");
	}
	//查找数据
	@ResponseBody
	@RequestMapping("/findddlist")
	public Object FindDDList(@RequestParam(required = false,defaultValue = "1") int pageNo,HttpServletRequest request){
		 Map<String, Object> reJson = new HashMap<String, Object>();
		 @SuppressWarnings("unchecked")
		 Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("cond");
		 Map<String,Object> findcond = new HashMap<String,Object>();
		 findcond.put("wid", cond.get("wid"));
		 findcond.put("dcid", cond.get("dcid"));
		 findcond.put("status", cond.get("status"));
		 findcond.put("stcsj",cond.get("stcsj"));
		 findcond.put("stcsjd1",cond.get("stcsjd1"));
		 findcond.put("stcsjd2",cond.get("stcsjd2"));
		 findcond.put("pageNo",(pageNo-1)*20);
		 @SuppressWarnings("unchecked")
			Map<String,Object> pxcond =(Map<String,Object>) cond.get("pxcond");
		 if(pxcond!=null) {
			 String str = (String)pxcond.get("select");
			 if(str!= null) {
				 findcond.put(str, pxcond.get(str));
			 }
		 }
		 
		 List<DeviceDetaiVo> ddlist=ddService.selectAll(findcond);
		 reJson.put("ddlist", ddlist);
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/searchmidc")
	public Object searchMidc(Long pid){
		 Map<String, Object> reJson = new HashMap<String, Object>();
		 List<Category>midc = categService.selectChildCateByPid(pid);
		 reJson.put("midc", midc);
        return JSON.toJSONString(reJson);
	}
	//添加分类
	@ResponseBody
	@RequestMapping("/categadd")
	public Object categAdd(String pid,String sid,String cty,String cname,Model model){
		Map<String, String> reJson = new HashMap<String, String>();
		Category cate = new Category();
		if(pid.equals("-1")){
			cate.setPid(Long.parseLong("0"));
			cate.setName(cname);
			cate.setCtype("1");
		}else{
			cate.setPid(Long.parseLong(sid));
			cate.setName(cname);
			Long ct= Long.parseLong(cty);
			cate.setCtype(Long.toString(ct+1));
		}
		if(categService.insertSelective(cate)>0)
			reJson.put("ok", "ok");
		else
			reJson.put("ok", "fal");
		 return JSON.toJSONString(reJson);
	}
	//修改分类
	@ResponseBody
	@RequestMapping(value="/categmod" ,produces="application/json;charset=UTF-8;")
	public Object categMod(String pid,String sid,String cty,String cname,Model model){
		Map<String, String> reJson = new HashMap<String, String>();
		Category cate = categService.selectByPrimaryKey(Long.parseLong(sid));
		cate.setName(cname);
		if(categService.updateByPrimaryKeySelective(cate)>0)
			reJson.put("ok", "ok");
		else
			reJson.put("ok", "fal");
		return JSON.toJSONString(reJson);
	}
	//删除分类检查
	@ResponseBody
	@RequestMapping("/catacheckdel")
	public Object cataCheckDel(String pid,String sid,String cty,Model model){
		Map<String, String> reJson = new HashMap<String, String>();
		if(cty.equals("3")){//设备分类检测是否有设备存在
			if(ddService.selectDDConutByDcid(Long.parseLong(sid))>0){
				reJson.put("fal", "conut>0");
			}else{
				reJson.put("ok", "ok");
			}
		}else{//功能分类，包含之类不能删除
			if(categService.selectSubCataCountBySid(Long.parseLong(sid))>0){
				reJson.put("fal", "sub>0");
			}else{
				reJson.put("ok", "ok");
			}
		}
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/uacccheck")
	public Object uaccCheck(String uacc){
		Map<String, String> reJson = new HashMap<String, String>();
		if(userService.SelectUserByUacc(uacc)!=null){
			reJson.put("fal", "fal");
		}else{
			reJson.put("ok", "ok");
		}
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/nocheck")
	public Object noCheck(String no){
		Map<String, String> reJson = new HashMap<String, String>();
		if(ddService.selectDeviceByNo(no)!=null){
			reJson.put("fal", "fal");
		}else{
			reJson.put("ok", "ok");
		}
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/whnamecheck")
	public Object whnameCheck(String whname){
		Map<String, String> reJson = new HashMap<String, String>();
		if(whMapper.selectNameCountByWhname(whname)<=0){
			reJson.put("ok", "ok");
		}
        return JSON.toJSONString(reJson);
	}
	
	//删除分类
	@RequestMapping("/categdel")
	public ModelAndView categDel(String pid,String sid,String cty,String cname,Model model){
		if(categService.deleteByPrimaryKey(Long.parseLong(sid))>0)
			return new ModelAndView("redirect:/back/deviceflshow.do");
		else
			return new ModelAndView("back/commons/404");
	}
	/**
	 * 读取Excel数据到数据库
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 * @author lp
	 */
	//@ResponseBody
	@RequestMapping("/readExcel")	
	public ModelAndView readExcel(@RequestParam(value="excelFile") MultipartFile file,HttpServletRequest request,HttpSession session) throws IOException{
		ModelAndView mv = new ModelAndView();
		//判断文件是否为空
		if(file == null){

			mv.setViewName("back/commons/404");
			return mv;
		}
        String name = file.getOriginalFilename();
		long size = file.getSize();
		if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){

			mv.setViewName("back/commons/404");
			return mv;
		}
		//读取Excel数据到List中
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		String bs =categService.importDeviceByExcel(file,admin.getName());
		request.getSession().setAttribute("importNo", bs);					
		return  new ModelAndView("redirect:/back/importExcelshow.do");
	}
	@RequestMapping("/importExcelshow")
	public ModelAndView importExcelShow(HttpServletRequest request,Model model){
		String importno = (String)request.getSession().getAttribute("importNo");
		List<Category>maxc = categService.getCategroyByCtype("1");
		model.addAttribute("maxc",maxc);
		List<TempData> tempd = categService.getAllTempDataByINo(importno);
		model.addAttribute("tempd",tempd);
		return new ModelAndView("back/device/excelshow");
	}
	
	@ResponseBody
	@RequestMapping("/submitInputExcel")	
	public Object submitInputExcel(HttpServletRequest request) throws IOException{
		String cid = (String) request.getParameter("cid");
		String fcid = (String) request.getParameter("fcid");
		String dcid = (String) request.getParameter("dcid");
		String[] sarr= (String[]) request.getParameterValues("sarr[]");
		String importno = (String)request.getSession().getAttribute("importNo");
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		Map<String, String>reJson= categService.addCategoryTable(importno,cid,fcid,dcid,sarr,user.getUid());
		return JSON.toJSONString(reJson);
	}
	
	@Autowired
	private WarehouseMapper whMapper;
	@RequestMapping("/deviceadd")
	public ModelAndView deviceAdd(@RequestParam(required = false,defaultValue = "1") int pageNo,
			HttpServletRequest request,Model model){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		List<Category>maxc = categService.getCategroyByCtype("1");
		
		if(admin.getUtype().equals("1")){
			List<Warehouse> whlist= whMapper.findAll();
			model.addAttribute("whlist",whlist);
		}else{
			Warehouse wh = whMapper.selectByPrimaryKey(user.getWid());
			model.addAttribute("wh",wh);
		}
		model.addAttribute("maxc",maxc);
		model.addAttribute("pageNo",pageNo);
		@SuppressWarnings("unchecked")
		Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("cond");
		model.addAttribute("status",cond.get("status"));
		model.addAttribute("wid",cond.get("wid"));
		model.addAttribute("dcid",cond.get("dcid"));
		model.addAttribute("stcsj",cond.get("stcsj"));
		model.addAttribute("stcsjd1",cond.get("stcsjd1"));
		model.addAttribute("stcsjd2",cond.get("stcsjd2"));
		return new ModelAndView("back/device/deviceadd");
	}
	
	@RequestMapping("/deviceinput")
	public ModelAndView LovecomAdd(DeviceDetail dd,HttpServletRequest request){
		
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		if(dd.getWid()!=null){
			dd.setStatus("1");
		}else{
			dd.setStatus("1");
			dd.setWid(user.getWid());
		}
		Long maxid = ddService.getMaxIdValue();
		if(maxid==null) maxid=(long)0;
		dd.setId(maxid+1);
		dd.setOriwid(dd.getWid());
		if(ddService.insertOneDevice(dd)>0){
			 InOutStock ios = new InOutStock();//插入数据操作记录操作记录
			 ios.setDid(dd.getId());
			 ios.setCorm(Long.parseLong("1"));
			 ios.setOldpos(dd.getWid());
			 ios.setPos(dd.getWid());
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 ios.setCotime(sdf.format(new Date()));
			 ios.setCouser(user.getUid());
			 iosService.insertOneIOStock(ios);
			return new ModelAndView("redirect:/back/devicelist.do");
		}
		return new ModelAndView("back/commons/404");
	}
	@RequestMapping("/devicemodf")
	public ModelAndView deviceModF(Long id, Model model){
		model.addAttribute("id",id);
		return new ModelAndView("back/device/deviceModF");
	}
	@RequestMapping("/devicemod")
	public ModelAndView deviceMod(Long id,HttpServletRequest request,Model model){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		List<Category>maxc = categService.getCategroyByCtype("1");
		List<Category>midc = categService.getCategroyByCtype("2");
		List<Category>shac = categService.getCategroyByCtype("3");
		if(admin.getUtype().equals("1")){
			List<Warehouse> whlist= whMapper.findAll();
			model.addAttribute("whlist",whlist);
		}else{
			Warehouse wh = whMapper.selectByPrimaryKey(user.getWid());
			model.addAttribute("wh",wh);
		}
		DeviceDetaiVo ddv =  ddService.selectById(id);
		DeviceDetail dd= ddService.selectByIdRturnDD(id);
		model.addAttribute("maxc",maxc);
		model.addAttribute("midc",midc);
		model.addAttribute("shac",shac);
		model.addAttribute("ddv",ddv);
		model.addAttribute("dd",dd);
		return new ModelAndView("back/device/devicemod");
	}
	@RequestMapping("/devicemodsub")
	public ModelAndView deviceModSub(DeviceDetail dd,HttpServletRequest request){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		DeviceDetail olddd =ddService.selectByIdRturnDD(dd.getId());//修改不改变设备位置
		dd.setWid(olddd.getWid());
		if(ddService.updateByPrimaryKeySelective(dd)>0){
			InOutStock ios = new InOutStock();//插入数据操作记录操作记录
			 ios.setDid(dd.getId());
			 ios.setCorm(Long.parseLong("5"));
			 ios.setOldpos(dd.getWid());
			 ios.setPos(dd.getWid());
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 ios.setCotime(sdf.format(new Date()));
			 ios.setCouser(user.getUid());
			 iosService.insertOneIOStock(ios);
			return new ModelAndView("redirect:/back/devicdetail.do?id="+dd.getId());
		}
		return new ModelAndView("back/commons/404");
	}
	@RequestMapping("/devicdetail")
	public ModelAndView DevicDetail(Long id, @RequestParam(required = false,defaultValue = "1") int pageNo,
            @RequestParam(required = false,defaultValue = "10") int limit,HttpServletRequest request,Model model){
		DeviceDetaiVo ddv =  ddService.selectById(id);
		List<InOutStockVo> ioslist = iosService.selectByDid(id);
		model.addAttribute("ddv",ddv);
		model.addAttribute("ioslist",ioslist);
		@SuppressWarnings("unchecked")
		Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("cond");
		model.addAttribute("status",cond.get("status"));
		model.addAttribute("wid",cond.get("wid"));
		
		model.addAttribute("dcid",cond.get("dcid"));
		model.addAttribute("stcsj",cond.get("stcsj"));
		model.addAttribute("stcsjd1",cond.get("stcsjd1"));
		model.addAttribute("stcsjd2",cond.get("stcsjd2"));
		model.addAttribute("pageNo",pageNo);
		return new ModelAndView("back/device/devicedetail");
	}
   //	报废设备
	@RequestMapping("/submitbf")
	public ModelAndView submitBF(Long id,HttpServletRequest request){
		DeviceDetail dd= ddService.selectByIdRturnDD(id);
		dd.setStatus("3");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    dd.setRemark("报废设备:"+sdf.format(new Date()));

		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		if(ddService.updateByPrimaryKeySelective(dd)>0){
			InOutStock ios = new InOutStock();//插入数据操作记录操作记录
			 ios.setDid(dd.getId());
			 ios.setCorm(Long.parseLong("4"));
			 ios.setOldpos(dd.getWid());
			 ios.setPos(dd.getWid());
			 ios.setCotime(sdf.format(new Date()));
			 ios.setCouser(user.getUid());
			 iosService.insertOneIOStock(ios);
			return new ModelAndView("redirect:/back/devicdetail.do?id="+dd.getId());
		}
		return new ModelAndView("back/commons/404");
	}
//	报废设备
	@RequestMapping("/deletebf")
	public ModelAndView deleteBF(Long id,@RequestParam(required = false,defaultValue = "1") int pageNo,HttpServletRequest request){
		DeviceDetail dd= ddService.selectByIdRturnDD(id);
		if(dd.getStatus().equals("3")){
			if(ddService.deleteOneById(id)>0){
				@SuppressWarnings("unchecked")
				Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("cond");
				String url ="redirect:/back/devicelist.do?pageNo="+pageNo;
				if(cond.get("status") !=null){
					url+="&status="+cond.get("status");
				}
				if(cond.get("wid") !=null){
					url+="&wid="+cond.get("wid");
				}
				if(cond.get("dcid") !=null){
					url+="&dcid="+cond.get("dcid");
				}
				return new ModelAndView(url);
			}
		}
		return new ModelAndView("back/commons/404");
	}
	//设备出入库
	@RequestMapping("/deviceiostock")
	public ModelAndView deviceIOStock(HttpServletRequest request,Model model){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users us = userService.SelectUserByUacc(admin.getName());
		Warehouse wh = whMapper.selectByWid(us.getWid());
		model.addAttribute("whname",wh.getWhname());
		request.getSession().setAttribute("outcoflag",null);
		request.getSession().setAttribute("coflag",null);
		return new ModelAndView("back/device/inoutStock");
	}
	@ResponseBody
	@RequestMapping("/instock")
	public Object inStock(String para,HttpServletRequest request){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		String coflag =(String) request.getSession().getAttribute("coflag");
		if(coflag==null || coflag==""){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String zf=sdf.format(new Date());
			 request.getSession().setAttribute("coflag", zf);
			 coflag = zf;
		}
		Map<String, Object> reJson = iostService.insertInOutStock(para.trim(),admin.getName(),coflag,"1");
        return JSON.toJSONString(reJson);
	}
	
	@ResponseBody
	@RequestMapping("/otherinstock")
	public Object otherInStock(String para,HttpServletRequest request){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		String coflag =(String) request.getSession().getAttribute("coflag");
		Map<String, Object> reJson = iostService.OtherInsertInOutStock(para.trim(),admin.getName(),coflag);
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/outstock")
	public Object outStock(String para,HttpServletRequest request){
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		String coflag =(String) request.getSession().getAttribute("outcoflag");
		if(coflag==null || coflag==""){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String zf=sdf.format(new Date());
			 request.getSession().setAttribute("outcoflag", zf);
			 coflag =zf;
		}
		Map<String, Object> reJson = iostService.insertInOutStock(para.trim(),admin.getName(),coflag,"2");
        return JSON.toJSONString(reJson);
	}
	
	@ResponseBody
	@RequestMapping("/submitinstock")
	public Object submitInStock(String para,HttpServletRequest request){
		Map<String, Object> reJson = iostService.submitInOutStock(request,para);
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/submitoutrest")
	public Object SubmitoutRest(HttpServletRequest request){
		String coflag =(String) request.getSession().getAttribute("outcoflag");
		Map<String, Object> reJson = new HashMap<String, Object>();
		if(coflag==null || coflag==""){
			// request.getSession().setAttribute("outcoflag", null);
			reJson.put("ok", "fal");
		}else{
			if(iostService.deleteIOSTByCoflag(coflag)>0){
				reJson.put("ok", "ok");
				request.getSession().setAttribute("outcoflag", null);
			}
		}
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/submitinputrest")
	public Object submitinputRest(HttpServletRequest request){
		String coflag =(String) request.getSession().getAttribute("coflag");
		Map<String, Object> reJson = new HashMap<String, Object>();
		if(coflag==null || coflag==""){
			reJson.put("ok", "fal");
		}else{
			if(iostService.deleteIOSTByCoflag(coflag)>0){
				reJson.put("ok", "ok");
				request.getSession().setAttribute("coflag", null);
			}
		}
        return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/searchios")
	public Object searchIOS(String para,HttpServletRequest request){
		 Map<String, Object> reJson = new HashMap<String, Object>();
		 Map<String, Object> cond = new HashMap<String, Object>();
		 
		 cond.put("para", para.trim());
		 Admin admin = (Admin) request.getSession().getAttribute("admin");
		 Users us = userService.SelectUserByUacc(admin.getName());
		 if(!us.getUtype().equals("1")){
			 cond.put("couser", us.getUid());
		 }
		 List<InOutStockVo> ddlist = iosService.selectByLikeDDNO(cond);
		 reJson.put("ddvo", ddlist);
        return JSON.toJSONString(reJson);
	}

	@ResponseBody
	@RequestMapping("/printqr")
	public Object printQR(Long id){
		 Map<String, Object> reJson = new HashMap<String, Object>();
		 DeviceDetaiVo dd = ddService.selectById(id);
		 if(dd !=null){
			 String title = dd.getWhname()+"-"+dd.getCdname();
			 String dno = "设备编号:"+ dd.getNo();
			 TscPrint.PrintByTSC(dd.getNo(),title,dno);
			 reJson.put("ok", "ok");
		 }else
			 reJson.put("ok", "fal");
		 return JSON.toJSONString(reJson);
	}
	//导出excel
	@RequestMapping("/exportExcel")
	public void exportExcel(HttpServletRequest request,HttpServletResponse response){
		ddService.LoadExcelServer(request, response);
	}
	@ResponseBody
	@RequestMapping("/clearsession")	
	public Object ClearSession(HttpServletRequest request) throws IOException{
		
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Map<String, String>reJson= new HashMap<String, String>();
		if(admin!=null){
			request.getSession().setAttribute("admin", null);
			 reJson.put("ok", "ok");
		}
		return JSON.toJSONString(reJson);
	}
	//批量操作
	@RequestMapping("/batchOperation")
	public ModelAndView batchOperation(Model model){	
		List<Category>maxc = categService.getCategroyByCtype("1");
		List<Category>midc = categService.getCategroyByCtype("2");
		List<Warehouse> whlist= whMapper.findAll();
        model.addAttribute("maxc",maxc);
		model.addAttribute("midc",midc);
		model.addAttribute("whlist",whlist);
		return new ModelAndView("back/device/batchoperation");
	}
	@ResponseBody
	@RequestMapping("/findvbatch")
	public Object findvbatch(Long wid,Long cid,Long fcid,Long dcid,HttpServletRequest request){
		Map<String, Object> reJson = new HashMap<String, Object>();
		if(wid==null && cid==null && fcid==null) {
			reJson.put("ok", "fal");
			return JSON.toJSONString(reJson);
		}
		Map<String,Object> cond = new HashMap<String,Object>();
		cond.put("wid", wid);
		cond.put("cid", cid);
		cond.put("fcid", fcid);
		cond.put("dcid", dcid);
		request.getSession().setAttribute("batchcond", cond);
		List<DeviceDetaiVo> ddlist = ddService.selectAllNoLimit(cond);
		reJson.put("ddlist", ddlist);
		return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/batchbofei")
	public Object batchbofei(HttpServletRequest request){
		Map<String, Object> reJson = new HashMap<String, Object>();
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		if(! user.getUtype().equals("1")) {
			reJson.put("ok", "fal");
			return JSON.toJSONString(reJson);
		}
		
		@SuppressWarnings("unchecked")
		Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("batchcond");
		List<DeviceDetaiVo> ddlist = ddService.selectAllNoLimit(cond);
		 for(DeviceDetaiVo ddvo:ddlist) {
			 DeviceDetail updd= ddService.selectByIdRturnDD(ddvo.getId());
			 if(updd.getStatus().equals("3")) continue;
			 
			 updd.setStatus("3");
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			 updd.setRemark("批量报废:"+sdf.format(new Date()));
			 ddService.updateByPrimaryKeySelective(updd);
			 InOutStock ios = new InOutStock();//插入数据操作记录操作记录
			 ios.setDid(updd.getId());
			 ios.setCorm(Long.parseLong("4"));
			 ios.setOldpos(updd.getWid());
			 ios.setPos(updd.getWid());
			 ios.setCotime(sdf.format(new Date()));
			 ios.setCouser(user.getUid());
			 iosService.insertOneIOStock(ios);
		 }
		reJson.put("ok", "ok");
		return JSON.toJSONString(reJson);
	}
	@ResponseBody
	@RequestMapping("/batchdelect")
	public Object batchdelect(HttpServletRequest request){
		Map<String, Object> reJson = new HashMap<String, Object>();
		Admin admin = (Admin) request.getSession().getAttribute("admin");
		Users user = userService.SelectUserByUacc(admin.getName());
		if(! user.getUtype().equals("1")) {
			reJson.put("ok", "fal");
			return JSON.toJSONString(reJson);
		}
		@SuppressWarnings("unchecked")
		Map<String,Object> cond = (Map<String, Object>) request.getSession().getAttribute("batchcond");
		List<DeviceDetaiVo> ddlist = ddService.selectAllNoLimit(cond);
		for(DeviceDetaiVo ddvo:ddlist) {
			ddService.deleteOneById(ddvo.getId());
			iosService.deleteOneById(ddvo.getId());
		}
		reJson.put("ok", "ok");
		return JSON.toJSONString(reJson);
	}
	@RequestMapping("/qrcodeimg")
	public void service(HttpServletRequest requset, HttpServletResponse response)throws IOException {
		response.setDateHeader("Expires", -1);
		response.setHeader("Cache-Control", "no-Cache");
		response.setHeader("pragma", "no-Cache");
        String content = requset.getParameter("no");
        EncoderHandler encoder = new EncoderHandler();
        encoder.encoderQRCoder(content, response);
    }
}
